package org.jeecg.modules.business.strategy.impl;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.business.entity.*;
import org.jeecg.modules.business.service.IBusOrderFeeService;
import org.jeecg.modules.business.service.impl.BusBookingRoomsServiceImpl;
import org.jeecg.modules.business.strategy.PricingStrategy;
import org.jeecg.modules.business.strategy.util.PricingUtil;
import org.jeecg.modules.rooms.entity.CesAllDayPriceRule;
import org.jeecg.modules.rooms.entity.CesHourRoomRule;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Component("dayAddStrategy")
public class DayAddStrategy implements PricingStrategy {

    @Resource
    IBusOrderFeeService feeService;

    @Resource
    private BusBookingRoomsServiceImpl bookingRoomsService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    PricingUtil pricingUtil;
    @Override
    public void calculateFee(BusRoomsLivingOrder livingOrder, CesAllDayPriceRule cesAllDayPriceRule, List<CesHourRoomRule> hourRoomRuleList) {
        Date date = new Date();
        Calendar nowCalendar = Calendar.getInstance();
        Calendar nextCalendar = Calendar.getInstance();
        BusBookingRooms bookingroom = bookingRoomsService.getById(livingOrder.getBookingRoomId());
        if (ObjectUtil.isEmpty(bookingroom)) {
            log.info("未找到订单{}对应的房间", livingOrder.getId());
            return;
        }
        // 查询当天房间超时消费
        BusOrderFee fee = pricingUtil.getOverTimeFee(livingOrder, bookingroom);
        // 需要支付完整费用时间的最后时间
        Date endTime = pricingUtil.getFullFeeTime(date, cesAllDayPriceRule);
        BusLivingLayoutDayPrice dayPrice = pricingUtil.addDayPrice(livingOrder, bookingroom, bookingroom.getRoomLayoutId());
        if (nextCalendar.getTime().compareTo(endTime) < 0){
            // 超时收取半天费用
            fee.setMoney(dayPrice.getPrice().divide(new BigDecimal(2)));
            nextCalendar.setTime(endTime);
        } else {
            // 添加每日房费
            fee.setMoney(dayPrice.getPrice());
            fee.setIsOverTime(false);
            // 获取每天超时时间，如果超过预离时间，修改预离时间
            nextCalendar = pricingUtil.getNextCalendar(livingOrder, nowCalendar,cesAllDayPriceRule);
        }
        // 移除处理过的时间订单，添加订单下一次超时的时间戳
        redisTemplate.opsForZSet().remove("overTimerOrder",livingOrder.getId());
        redisTemplate.opsForZSet().add("overTimerOrder",livingOrder.getId(),nextCalendar.getTimeInMillis());
        feeService.saveOrUpdate(fee);
    }
}
